package diona.auth

import com.google.gdata.client.http.AuthSubUtil
import diona.model.{User, GoogleAuth}
import net.liftweb.http._
import net.liftweb.actor.LiftActor
import net.liftweb.common.{Logger, Box}
import com.google.gdata.client.photos.PicasawebService
import java.net.URL
import com.google.gdata.data.photos.{GphotoEntry, AlbumFeed, PhotoEntry}
import com.google.gdata.data.MediaContent
import scala.collection.JavaConversions._

/**
 * User: anton
 * Date: 09.04.11 20:57
 */
object GoogleOperations extends Authorizer with LiftActor with ListenerManager with Logger
{
  protected def createUpdate = "Registered"

  override def lowPriority =
  {
    case msg: GoogleAuthorization => {
      info("Updating listeners")
      updateListeners(msg)
    }
  }

  val authAddress = "auth" :: "google" :: Nil

  @volatile var processToken: LiftRules.DispatchPF = {
    case Req("auth" :: "google" :: Nil, _, _) => () => processAuthorization()
  }

  @volatile var redirectToAuthorization: LiftRules.DispatchPF = {
    case Req("auth" :: "redirect" :: "google" :: Nil, _, _) => () => S.redirectTo(buildRedirectUrl());
  }

  def getPhotos(user: User): List[PhotoEntry] =
  {
    GoogleAuth.byUser(user) match {
      case Some(auth) => getPhotos(auth)
      case None => Nil
    }
  }

  def getUri(photoEntry: PhotoEntry): String =
  {
    photoEntry.getContent.asInstanceOf[MediaContent].getUri
  }

  private def getPhotos(auth: GoogleAuth): List[PhotoEntry] =
  {
    val service = new PicasawebService("share-share-1")
    service.setAuthSubToken(auth.authToken.value)

    val feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/default?kind=photo")

    val feed = service.getFeed(feedUrl, classOf[AlbumFeed])
    feed.getEntries.toList.map(new PhotoEntry(_))
  }

  def buildRedirectUrl(): String =
  {
    val scope = "https://www.google.com/m8/feeds/ https://picasaweb.google.com/data/";
    val secure = false;
    val session = true;
    AuthSubUtil.getRequestUrl(backRedirectUrl, scope, secure, session)
  }

  private def processAuthorization(): Box[LiftResponse] =
  {
    info("Processing authorization result")
    for {
      newToken <- S.param("token") ?~ "auth token not defined" ~> 400
      user <- User.currentUser
    } yield {
      val currentToken: Option[GoogleAuth] = GoogleAuth.byUser(user)
      val token = AuthSubUtil.exchangeForSessionToken(newToken, null)
      val newAuthInfo = currentToken match {
        case None => GoogleAuth.save(token, user)
        case _ => GoogleAuth.update(token, user)
      }
      GoogleOperations ! GoogleAuthorization(user)
      info("google auth sent")
      createCloseWindowResponse()
    }
  }
}

case class GoogleAuthorization(user: User)
